# coding=utf-8
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.shortcuts import render_to_response


def logins(request):
    errors = []
    username = request.POST.get('form-username')
    password = request.POST.get('form-password')
    user = authenticate(username=username, password=password)

    if user is not None and user.is_active:
        login(request, user)
        return render_to_response('index.html')
    if password is not None:
        errors.append("输入的账号密码有错误!")

    return render_to_response('login.html', {'errors': errors})


def register(request):
    errors = []
    if request.method == "POST":

        username = request.POST.get('form-username')
        password1 = request.POST.get('form-password1')
        password2 = request.POST.get('form-password2')
        email = request.POST.get('form-email')
        # 判断用户
        newname = User.objects.filter(username=username)
        if len(newname) > 0:
            errors.append('用户名重复')
            return render_to_response('register.html', {'errors': errors})

        if password1 != password2:
            errors.append('两次密码的值不想同')
            return render_to_response('register.html', {'errors': errors})
        # 创建用户
        user = User.objects.create_user(username, email, password2)
        user.is_active = False
        user.save()
    return render_to_response('register.html', {'errors': errors})
